package top.heliming.youyou.item.controller;

import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import top.heliming.youyou.common.pojo.PageResult;
import top.heliming.youyou.item.pojo.Brand;
import top.heliming.youyou.item.service.BrandService;

/**
 * description: //品牌
 *
 * @author: heliming
 * @date:2019/05/27 下午 10:51
 */
@RestController
@RequestMapping("brand")
public class BrandController {

  @Autowired
  private BrandService brandService;

  @GetMapping("page")
  public ResponseEntity<PageResult<Brand>> queryBrandByPage(
      @RequestParam(value = "page", defaultValue = "1") Integer page,
      @RequestParam(value = "rows", defaultValue = "5") Integer rows,
      @RequestParam(value = "sortBy", required = false) String sortBy,
      @RequestParam(value = "desc", defaultValue = "false") Boolean desc,
      @RequestParam(value = "key", required = false) String key) {
    PageResult<Brand> result = this.brandService.queryBrandByPageAndSort(page,rows,sortBy,desc, key);
    if (result == null || result.getItems().size() == 0) {
      return new ResponseEntity<>(HttpStatus.NOT_FOUND);
    }
    return ResponseEntity.ok(result);
  }

  /**
   * 新增品牌
   * @param brand
   * @return
   */
  @PostMapping
  public ResponseEntity<Void> saveBrand(Brand brand, @RequestParam("cids") List<Long> cids) {
    this.brandService.saveBrand(brand, cids);
    return new ResponseEntity<>(HttpStatus.CREATED);
  }

  /**
   * 根据分类查询品牌
   * @param cid
   * @return
   */
  @GetMapping("cid/{cid}")
  public ResponseEntity<List<Brand>> queryBrandListByCid(@PathVariable("cid")Long cid){

    List<Brand> brandList = this.brandService.queryBrandByCategory(cid);
    if(CollectionUtils.isEmpty(brandList)){
      // 响应404
      return ResponseEntity.badRequest().build();
    }
    // 响应200
    return ResponseEntity.ok(brandList);
  }

  /**
   * 根据多个id查询品牌
   * @param ids
   * @return
   */
  @GetMapping("list")
  public ResponseEntity<List<Brand>> queryBrandByIds(@RequestParam("ids") List<Long> ids){
    List<Brand> list = this.brandService.queryBrandByIds(ids);
    if(list == null){
      new ResponseEntity<>(HttpStatus.NOT_FOUND);
    }
    return ResponseEntity.ok(list);
  }
}
